<?php

class SwooleServer
{
	private $serv;

	public function __construct(){
		//创建WebSocket Server对象，监听0.0.0.0:9502端口
		$ws = new Swoole\WebSocket\Server('0.0.0.0', 8083);

		$ws->set(
			array(
				'worker_num' => 4, //这里设置为 CPU 核数的 1-4 倍最合理
				'daemonize' => 1, //以守护进程执行
				'max_request' => 200000,//设置 worker 进程的最大任务数
				"log_file" => "/data/wwwroot/bfyc/runtime/log/taskqueueu.log",
			)
		);

		//监听WebSocket连接打开事件
		$ws->on('Open', function ($ws, $request) {
			$ws->push($request->fd, "hello, welcome\n");
		});

		//监听WebSocket消息事件
		$ws->on('Message', function ($ws, $frame) {
			echo "Message: {$frame->data}\n";
			$ws->push($frame->fd, "server: {$frame->data}");
		});

		//监听WebSocket连接关闭事件
		$ws->on('Close', function ($ws, $fd) {
			echo "client-{$fd} is closed\n";
		});

		$ws->start();

	}

	//此回调函数在worker进程中执行
	public function onReceive($serv, $fd, $from_id, $data){
		$urlList = json_decode($data,true);
//		print_r($urlList);
		if(!$urlList){
			echo PHP_EOL.'Null'.PHP_EOL;
		}
		foreach ($urlList as $key => $val){
			if(!empty($val['url'])){
				$serv->task($val);
			}
		}
	}

	//处理异步任务(此回调函数在task进程中执行)
	public function onTask($serv, $task_id, $from_id, $data){
		try{
			if(!empty($data)){
				return $this->Implement($data['url']);
			}
		}catch(\Exception $e){
			return $e->getMessage();
		}
		echo PHP_EOL.'success'.PHP_EOL;
	}

	//处理异步任务的结果(此回调函数在worker进程中执行)
	public function onFinish($serv, $task_id, $data){
		echo PHP_EOL.$data.PHP_EOL;
	}

	public function Implement($url)
	{
		$ch = curl_init();

		curl_setopt($ch, CURLOPT_URL, $url);

		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

		$res = curl_exec($ch);

		curl_close($ch);

		return $res;
	}
}
$server = new SwooleServer();
